package cn.xp1997.shiro.x.token;

import cn.xp1997.shiro.x.exception.ShiroTokenException;
import cn.xp1997.shiro.x.jwt.JwtUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * token解码器
 * @author xp
 */
public class TokenDecoder {

    public TokenDecoder(String token){
        this.token = token;
    }

    private String token;

    private String getToken(){
        return token;
    }

    /**
     * 解析token的key
     * @param key key
     * @return value
     */
    public String decodeKey(String key){
        return JwtUtil.getKey(getToken(), key);
    }

    /**
     * 将token解析为对象
     */
    public <T> T  getObject(Class<T> clazz) {
        T t;
        try {
            t = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                String value = decodeKey(name);
                field.setAccessible(true);
                field.set(t, value);

            }
        } catch (Exception e) {
            throw new ShiroTokenException("file to get object");
        }
        return t;
    }

    /**
     * 解析token为map
     * @return map
     */
    public Map<String, String> getMap(){
        return JwtUtil.getAll(token);
    }

}
